package com.seek.inter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.seek.common.handler.SpringContextHolder;
import com.seek.model.dto.ResultInfo;
import com.seek.model.entity.TCompanyAgent;
import com.seek.service.CompanyAgentService;
import com.seek.service.ReadService;
import com.seek.util.CommonUtil;

/**
 * 本类主要是作为代理商维护相关接口实现类
 *
 */
public class AgentInter {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	private CompanyAgentService companyAgentService = (CompanyAgentService)SpringContextHolder.getBean("companyAgentService");
	private ReadService readService = (ReadService)SpringContextHolder.getBean("readService");
	
	/**
	 * 获取代表商列表
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo getAgentList(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		Long myAgentId = reqJson.getLong("myAgentId");
		String agentName = reqJson.getString("agentName");
		
		// 拼接检索条件
		StringBuffer where = new StringBuffer("");
		List<Object> params = new ArrayList<Object>();
		params.add(companyId);
		if (myAgentId != null && myAgentId > 0){
			where.append(" and (a.fid=?)");
			params.add(myAgentId);
		}
		if (!CommonUtil.isEmpty(agentName)){
			agentName = "%"+agentName+"%";
			where.append(" and a.agent_name like ?");
			params.add(agentName);
		}
		
		// 取得总记录行数
		String sql = "select count(1) cnt from t_company_agent a where a.is_used=1 and a.company_id=?"+where.toString();
		// 列表数据SQL: 把最需要审核的放在前面
		StringBuffer sb = new StringBuffer("select a.id agentId,a.agent_name agentName,a.phone_no phoneNo,a.money_type moneyType,a.money,");
		sb.append(" a.bank_name bankName,a.card_number cardNumber,a.create_time createTime,a.modify_time modifyTime,a.fid,")
		  .append(" (select agent_name from t_company_agent m where m.id=a.fid) parentName")
		  .append(" from t_company_agent a where a.is_used=1 and a.company_id=?")
		  .append(where.toString()).append(" order by a.id desc");
				
		result.setStatus(0);
		result.setMessage("成功");
		result.setBody(readService.pageQueryBySql(sb.toString(), sql, reqJson.getIntValue("pageSize"), reqJson.getIntValue("pageNo"), params.toArray()));
		return result;
	}
	
	/**
	 * 获取某代理商详情
	 */
	public ResultInfo getAgentDetail(HttpServletRequest request,JSONObject reqJson) throws Exception{
		ResultInfo result = new ResultInfo();
		Long agentId = reqJson.getLong("agentId");
		Long myAgentId = reqJson.getLong("myAgentId");
		if (agentId == null || agentId<1) {
			result.setStatus(1);
			result.setMessage("参数错误，请检查!");
			return result;
		}
		
		StringBuffer sb = new StringBuffer("select a.id agentId,a.agent_name agentName,a.phone_no phoneNo,a.money_type moneyType,a.money,");
		sb.append(" a.bank_name bankName,a.card_number cardNumber,a.remark,a.fid,b.money fMoney from t_company_agent a left join t_company_agent b on a.fid=b.id where a.is_used=1 and a.id=?");
		if (myAgentId != null && myAgentId>0){
			sb.append(" and (a.id="+myAgentId+" or a.fid="+myAgentId+")");
		}

		result.setStatus(0);
		result.setMessage("成功");
		result.setBody(readService.findOneMapBySql(sb.toString(), new Object[]{agentId}));
		return result;
	}
	
	/**
	 * 新增或编辑活动后的保存
	 */
	public ResultInfo saveAgent(HttpServletRequest request,JSONObject reqJson) throws Exception{
		ResultInfo result = new ResultInfo();
		try{
			TCompanyAgent en = companyAgentService.save(reqJson);
			Map<String, Object> ret = new HashMap<String, Object>();
			ret.put("agentId", en.getId());
			result.setStatus(0);
			result.setMessage("成功");
			result.setBody(ret);
			return result;
		}catch(Exception e){
			logger.error("系统异常",e);
			result.setStatus(1);
			result.setMessage(e.getMessage());
			return result;
		}
	}

	/**
	 * 查询代理商注册客户信息
	 **/
	public ResultInfo queryAgentCustomerList(HttpServletRequest request, JSONObject reqJson)
			throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		Long myAgentId = reqJson.getLong("myAgentId");
		Long agentId = reqJson.getLong("agentId");
		String rqq = reqJson.getString("rqq");
		String rqz = reqJson.getString("rqz");

		// 拼接检索条件
		StringBuffer where = new StringBuffer("");
		List<Object> params = new ArrayList<Object>();
		params.add(companyId);
		if (!CommonUtil.isEmpty(rqq)) {
			where.append(" and a.active_date >= ?");
			params.add(rqq);
		}
		if (!CommonUtil.isEmpty(rqz)) {
			rqz = rqz.substring(0, 10) + " 23:59:59";
			where.append(" and a.active_date <= ?");
			params.add(rqz);
		}
		StringBuffer queryDetailSql = new StringBuffer("");
		StringBuffer countSql = new StringBuffer("");
		if (myAgentId != null && myAgentId > 0) {
			int level = 0;
			String sql = "select (case when ifnull(a.fid,0) = 0 then 1 else 2 end) level from t_company_agent a where a.id=?";
			Map<String,Object> ds = readService.findOneMapBySql(sql, new Object[]{myAgentId});
			if (ds != null && ds.keySet().size() > 0){
				level = CommonUtil.getIntValue(ds.get("level"));
			}
			// 如果有传入agentId
			if (agentId != null && agentId > 0){
				// 判断查询的是一级代理商还是二级代理商
				if (agentId.longValue() != myAgentId.longValue()){
					where.append(" and a.sub_agent_id=?");
					params.add(agentId);
				}else if (level == 2){//当前登录人是二级
					where.append(" and a.sub_agent_id=?");
					params.add(agentId);
				}else if (level == 1){
					where.append(" and a.agent_id=? and ifnull(a.sub_agent_id,0)=0");
					params.add(agentId);
				}
			}else{
				// 没有传入agentId:查询的是当前代理商下所有客户
				if (level == 2){//当前登录人是二级
					where.append(" and a.sub_agent_id=?");
					params.add(myAgentId);
				}else if (level == 1){
					where.append(" and a.agent_id=?");
					params.add(myAgentId);
				}
			}
		}else{
			if (agentId != null && agentId > 0){
				int level = 0;
				String sql = "select (case when ifnull(a.fid,0) = 0 then 1 else 2 end) level from t_company_agent a where a.id=?";
				Map<String,Object> ds = readService.findOneMapBySql(sql, new Object[]{agentId});
				if (ds != null && ds.keySet().size() > 0){
					level = CommonUtil.getIntValue(ds.get("level"));
				}
				if (level == 2){//当前登录人是二级
					where.append(" and a.sub_agent_id=?");
					params.add(agentId);
				}else if (level == 1){
					where.append(" and a.agent_id=?");
					params.add(agentId);
				}
			}else{
				where.append(" and ifnull(a.agent_id,0)=0");
			}
		}
		countSql.append("select count(1) cnt from t_customer a where a.company_id=?").append(where.toString());
		queryDetailSql.append("select REPLACE(a.phone_no, SUBSTR(a.phone_no,4,4), '****') as phoneNo ,a.name ,a.reg_date as regDate, a.active_date as activeDate  from t_customer a where a.company_id=?")
		              .append(where).append(" order by a.active_date asc");

		result.setStatus(0);
		result.setMessage("成功");
		int pageSize = CommonUtil.getIntValue(reqJson.getIntValue("pageSize"));
		int pageNo = CommonUtil.getIntValue(reqJson.getIntValue("pageNo"));
		result.setBody(readService.pageQueryBySql(queryDetailSql.toString(), countSql.toString(),
				pageSize,pageNo, params.toArray()));

		return result;
	}
}
